﻿/*
 * Copyright (C) 2012, Jesus Requejo <jesus.requejo@gmail.com> 
 * Licensed under Microsoft Public License (Ms-PL)
 * http://www.microsoft.com/en-us/openness/licenses.aspx#MPL
*/

namespace WindowsFormsInfrastructure {

   using System;
   using System.Windows.Forms;
   
   public class TrayHelper {

      private FormWindowState LastWindowState { get; set; }
      private Form Form { get; set; }
      private Action<object, FormClosingEventArgs> ClosingCallback { get; set; }
      private Action SendToTrayCallback { get; set; }
      private Action RestoreFromTrayCallback { get; set; }

      public TrayHelper(Form form,
         Action<object, FormClosingEventArgs> closingCallback,
         Action sendToTrayCallback,
         Action restoreFromTrayCallback
      )
         : this(form, closingCallback) {
         SendToTrayCallback = sendToTrayCallback;
         RestoreFromTrayCallback = restoreFromTrayCallback;
      }

      public TrayHelper(Form form,
         Action<object, FormClosingEventArgs> closingCallback
         )
         : this(form) {
         ClosingCallback = closingCallback;
      }

      public TrayHelper(Form form) {
         Form = form;
         LastWindowState = Form.WindowState;
      }

      public void Form1_Resize(object sender, EventArgs e) {
         if (Form.WindowState == FormWindowState.Minimized && LastWindowState != FormWindowState.Minimized) {
            SendToTray();
         }
      }

      public void notifyIcon1_MouseClickedInTrayIcon(object sender, MouseEventArgs e) {
         if (e.Button == MouseButtons.Left) {
            if (Form.WindowState == FormWindowState.Minimized) {
               RestoreFromTray();
            }
            else {
               SendToTray();
            }
         }
      }

      public void Form1_FormClosing(object sender, FormClosingEventArgs e) {
         if (ClosingCallback != null) {
            ClosingCallback(sender, e);
         }
      }

      public void SendToTray() {
         if (SendToTrayCallback != null) {
            SendToTrayCallback();
         }
         Form.Hide();
         Form.ShowInTaskbar = false;
         Form.WindowState = FormWindowState.Minimized;
         LastWindowState = FormWindowState.Minimized;
      }

      public void RestoreFromTray() {
         Form.Show();
         Form.WindowState = FormWindowState.Normal;
         LastWindowState = FormWindowState.Normal;
         Form.ShowInTaskbar = true;
         if (RestoreFromTrayCallback != null) {
            RestoreFromTrayCallback();
         }
      }
   }
}
